#include "StateBar.h"
#include "BaseBuff.h"
#include "MagnetBuff.h"
#include "MainLayer.h"
#include "TestGameScene.h"


StateBar::StateBar(void)
{
	_listBuff = NULL;
}


StateBar::~StateBar(void)
{
	CC_SAFE_RELEASE(_listBuff);
}

bool StateBar::init()
{
	if (!CCNode::init())
		return false;

	setBuffs(CCArray::create());


	return true;
}

void StateBar::addBuff( BaseBuff* buff, bool start)
{
	CCAssert(buff, "Buff must be non-null!");

	// Check exist
	CCObject* it;
	CCARRAY_FOREACH(_listBuff, it)
	{
		BaseBuff* bb = dynamic_cast<BaseBuff*>(it);
		if (strcmp(bb->getId()->getCString(), buff->getId()->getCString()) == 0)
		{
			bb->setTimeMax(buff->getTimeMax());
			return;
		}
	}
	
	_listBuff->addObject(buff);
	addChild(buff);

	updateBuffPosition();

	if (start)
		buff->start(this);
}

void StateBar::updateBuffPosition()
{
	CCObject* it;
	for (int i = 0; i < _listBuff->count(); i++)
	{
		BaseBuff* buff = dynamic_cast<BaseBuff*>(_listBuff->objectAtIndex(i));
		buff->setPositionX(0);
		buff->setPositionY(-100 * i);
	}
}

void StateBar::removeBuff( BaseBuff* buff, bool isStop )
{
	_listBuff->removeObject(buff);
	if (isStop)
		buff->stop();
	removeChild(buff);
	updateBuffPosition();
}

void StateBar::processing( float dt )
{
	// Check to remove buff
	int i = 0;
	while (i < _listBuff->count())
	{
		BaseBuff* buff = dynamic_cast<BaseBuff*>(_listBuff->objectAtIndex(i));
		if (buff->getIsComplete())
			removeBuff(buff);

		i++;
	}
}

void StateBar::onEnter()
{
	CCNode::onEnter();
	schedule(SEL_SCHEDULE(&StateBar::processing));
}

void StateBar::onExit()
{
	CCNode::onExit();
	unschedule(SEL_SCHEDULE(&StateBar::processing));
}

MainLayer* StateBar::getMainLayer()
{
	return dynamic_cast<MainLayer*>(getParent()->getParent()->getChildByTag(MAINLAYER_TAG));
}

